// 多仪表盘管理模块 - 负责仪表盘的创建、切换、配置和管理

class MultiDashboard {
    constructor() {
        this.dashboards = [];
        this.activeDashboardId = null;
        this.listeners = {};
        this.defaultDashboards = [
            {
                id: 'overview',
                name: '总览仪表盘',
                icon: 'dashboard',
                description: '系统整体运行状态和关键指标总览',
                layout: 'grid',
                widgets: [
                    {
                        id: 'system_status',
                        type: 'status_card',
                        title: '系统状态',
                        dataSource: 'system',
                        metrics: ['cpu', 'memory', 'network', 'disk'],
                        size: 'medium',
                        position: { x: 0, y: 0, width: 2, height: 1 }
                    },
                    {
                        id: 'alert_summary',
                        type: 'alert_counter',
                        title: '告警统计',
                        size: 'small',
                        position: { x: 2, y: 0, width: 1, height: 1 }
                    },
                    {
                        id: 'system_performance',
                        type: 'line_chart',
                        title: '系统性能',
                        dataSource: 'system',
                        fields: ['cpu', 'memory'],
                        timeRange: '1h',
                        size: 'large',
                        position: { x: 0, y: 1, width: 3, height: 2 }
                    }
                ]
            },
            {
                id: 'finance',
                name: '金融数据',
                icon: 'trending_up',
                description: '金融市场实时数据和趋势分析',
                layout: 'grid',
                widgets: [
                    {
                        id: 'stock_summary',
                        type: 'financial_cards',
                        title: '股票概览',
                        symbols: ['AAPL', 'MSFT', 'GOOGL', 'AMZN'],
                        size: 'medium',
                        position: { x: 0, y: 0, width: 2, height: 1 }
                    },
                    {
                        id: 'market_trend',
                        type: 'line_chart',
                        title: '市场趋势',
                        dataSource: 'finance',
                        fields: ['price'],
                        groupBy: 'symbol',
                        timeRange: '24h',
                        size: 'large',
                        position: { x: 0, y: 1, width: 3, height: 2 }
                    },
                    {
                        id: 'volume_distribution',
                        type: 'pie_chart',
                        title: '交易量分布',
                        dataSource: 'finance',
                        field: 'volume',
                        groupBy: 'symbol',
                        size: 'medium',
                        position: { x: 2, y: 0, width: 1, height: 1 }
                    }
                ]
            },
            {
                id: 'iot',
                name: '物联网设备',
                icon: 'devices',
                description: 'IoT设备状态监控和数据采集',
                layout: 'grid',
                widgets: [
                    {
                        id: 'device_status',
                        type: 'device_grid',
                        title: '设备状态',
                        size: 'medium',
                        position: { x: 0, y: 0, width: 2, height: 2 }
                    },
                    {
                        id: 'device_temperature',
                        type: 'line_chart',
                        title: '设备温度',
                        dataSource: 'iot',
                        fields: ['temperature'],
                        groupBy: 'deviceId',
                        timeRange: '1h',
                        size: 'medium',
                        position: { x: 2, y: 0, width: 1, height: 1 }
                    },
                    {
                        id: 'device_humidity',
                        type: 'line_chart',
                        title: '设备湿度',
                        dataSource: 'iot',
                        fields: ['humidity'],
                        groupBy: 'deviceId',
                        timeRange: '1h',
                        size: 'medium',
                        position: { x: 2, y: 1, width: 1, height: 1 }
                    }
                ]
            }
        ];
        
        this.widgetTypes = this.registerDefaultWidgetTypes();
    }

    // 初始化多仪表盘管理
    init() {
        console.log('多仪表盘管理模块初始化...');
        
        // 加载默认仪表盘
        this.loadDefaultDashboards();
        
        // 尝试加载用户自定义仪表盘
        this.loadDashboardsFromStorage();
        
        // 设置第一个仪表盘为活动状态
        if (this.dashboards.length > 0 && !this.activeDashboardId) {
            this.setActiveDashboard(this.dashboards[0].id);
        }
        
        console.log('多仪表盘管理模块初始化完成');
    }

    // 注册默认组件类型
    registerDefaultWidgetTypes() {
        return {
            // 基础组件类型
            line_chart: {
                name: '折线图',
                icon: 'show_chart',
                render: (container, config) => this.renderLineChart(container, config)
            },
            bar_chart: {
                name: '柱状图',
                icon: 'bar_chart',
                render: (container, config) => this.renderBarChart(container, config)
            },
            pie_chart: {
                name: '饼图',
                icon: 'pie_chart',
                render: (container, config) => this.renderPieChart(container, config)
            },
            status_card: {
                name: '状态卡片',
                icon: 'assessment',
                render: (container, config) => this.renderStatusCard(container, config)
            },
            data_table: {
                name: '数据表格',
                icon: 'table_chart',
                render: (container, config) => this.renderDataTable(container, config)
            },
            
            // 专用组件类型
            financial_cards: {
                name: '金融卡片',
                icon: 'monetization_on',
                render: (container, config) => this.renderFinancialCards(container, config)
            },
            device_grid: {
                name: '设备网格',
                icon: 'devices_other',
                render: (container, config) => this.renderDeviceGrid(container, config)
            },
            alert_counter: {
                name: '告警计数器',
                icon: 'notifications_active',
                render: (container, config) => this.renderAlertCounter(container, config)
            },
            gauge_chart: {
                name: '仪表盘',
                icon: 'speed',
                render: (container, config) => this.renderGaugeChart(container, config)
            }
        };
    }

    // 加载默认仪表盘
    loadDefaultDashboards() {
        this.defaultDashboards.forEach(dashboardConfig => {
            // 检查是否已存在同名仪表盘
            if (!this.dashboards.find(d => d.id === dashboardConfig.id)) {
                this.createDashboard(dashboardConfig);
            }
        });
    }

    // 创建仪表盘
    createDashboard(config) {
        const dashboard = {
            id: config.id || `dashboard_${Date.now()}`,
            name: config.name || '未命名仪表盘',
            icon: config.icon || 'dashboard',
            description: config.description || '',
            layout: config.layout || 'grid',
            widgets: config.widgets || [],
            createdAt: Date.now(),
            updatedAt: Date.now(),
            isDefault: !!config.isDefault,
            isLocked: !!config.isLocked
        };
        
        this.dashboards.push(dashboard);
        
        // 保存到本地存储
        this.saveDashboardsToStorage();
        
        console.log(`仪表盘已创建: ${dashboard.name} (${dashboard.id})`);
        this.emit('dashboard:created', dashboard);
        
        return dashboard;
    }

    // 更新仪表盘
    updateDashboard(dashboardId, updates) {
        const dashboardIndex = this.dashboards.findIndex(d => d.id === dashboardId);
        if (dashboardIndex === -1) {
            console.error(`仪表盘 ${dashboardId} 不存在`);
            return false;
        }
        
        // 不允许修改默认仪表盘的核心属性
        const dashboard = this.dashboards[dashboardIndex];
        if (dashboard.isLocked) {
            console.warn(`仪表盘 ${dashboardId} 已锁定，无法修改`);
            return false;
        }
        
        // 更新仪表盘
        this.dashboards[dashboardIndex] = {
            ...dashboard,
            ...updates,
            updatedAt: Date.now()
        };
        
        // 保存到本地存储
        this.saveDashboardsToStorage();
        
        console.log(`仪表盘已更新: ${dashboardId}`);
        this.emit('dashboard:updated', this.dashboards[dashboardIndex]);
        
        // 如果更新的是当前活动仪表盘，重新渲染
        if (dashboardId === this.activeDashboardId) {
            this.renderActiveDashboard();
        }
        
        return true;
    }

    // 删除仪表盘
    deleteDashboard(dashboardId) {
        const dashboardIndex = this.dashboards.findIndex(d => d.id === dashboardId);
        if (dashboardIndex === -1) {
            console.error(`仪表盘 ${dashboardId} 不存在`);
            return false;
        }
        
        const dashboard = this.dashboards[dashboardIndex];
        
        // 不允许删除默认仪表盘
        if (dashboard.isDefault || dashboard.isLocked) {
            console.warn(`仪表盘 ${dashboardId} 不能被删除`);
            return false;
        }
        
        // 删除仪表盘
        this.dashboards.splice(dashboardIndex, 1);
        
        // 保存到本地存储
        this.saveDashboardsToStorage();
        
        console.log(`仪表盘已删除: ${dashboardId}`);
        this.emit('dashboard:deleted', dashboard);
        
        // 如果删除的是当前活动仪表盘，切换到第一个可用仪表盘
        if (dashboardId === this.activeDashboardId && this.dashboards.length > 0) {
            this.setActiveDashboard(this.dashboards[0].id);
        } else if (this.dashboards.length === 0) {
            this.activeDashboardId = null;
        }
        
        return true;
    }

    // 设置活动仪表盘
    setActiveDashboard(dashboardId) {
        const dashboard = this.dashboards.find(d => d.id === dashboardId);
        if (!dashboard) {
            console.error(`仪表盘 ${dashboardId} 不存在`);
            return false;
        }
        
        this.activeDashboardId = dashboardId;
        
        // 保存活动仪表盘ID到本地存储
        localStorage.setItem('active_dashboard_id', dashboardId);
        
        console.log(`活动仪表盘已设置: ${dashboard.name}`);
        this.emit('dashboard:activated', dashboard);
        
        // 渲染仪表盘
        this.renderActiveDashboard();
        
        return true;
    }

    // 渲染活动仪表盘
    renderActiveDashboard() {
        const dashboard = this.dashboards.find(d => d.id === this.activeDashboardId);
        if (!dashboard) return;
        
        const container = document.getElementById('dashboard-container');
        if (!container) return;
        
        // 清空容器
        container.innerHTML = '';
        
        // 添加仪表盘标题
        const header = document.createElement('div');
        header.className = 'dashboard-header';
        header.innerHTML = `
            <h1>${dashboard.name}</h1>
            <p>${dashboard.description}</p>
        `;
        container.appendChild(header);
        
        // 创建仪表盘网格容器
        const gridContainer = document.createElement('div');
        gridContainer.className = 'dashboard-grid';
        container.appendChild(gridContainer);
        
        // 渲染所有组件
        dashboard.widgets.forEach(widget => {
            this.renderWidget(gridContainer, widget);
        });
    }

    // 渲染组件
    renderWidget(container, widget) {
        const widgetContainer = document.createElement('div');
        widgetContainer.className = `dashboard-widget widget-${widget.size || 'medium'}`;
        widgetContainer.dataset.widgetId = widget.id;
        
        // 设置组件位置和大小（如果使用网格布局）
        if (widget.position) {
            if (widget.position.x !== undefined) widgetContainer.style.gridColumn = widget.position.x + 1;
            if (widget.position.y !== undefined) widgetContainer.style.gridRow = widget.position.y + 1;
            if (widget.position.width !== undefined) widgetContainer.style.gridColumnEnd = `span ${widget.position.width}`;
            if (widget.position.height !== undefined) widgetContainer.style.gridRowEnd = `span ${widget.position.height}`;
        }
        
        // 添加组件头部
        const widgetHeader = document.createElement('div');
        widgetHeader.className = 'widget-header';
        widgetHeader.innerHTML = `
            <h3>${widget.title || '未命名组件'}</h3>
            <div class="widget-actions">
                <button class="widget-refresh"><i class="material-icons">refresh</i></button>
                <button class="widget-config"><i class="material-icons">settings</i></button>
            </div>
        `;
        widgetContainer.appendChild(widgetHeader);
        
        // 创建组件内容区域
        const widgetContent = document.createElement('div');
        widgetContent.className = 'widget-content';
        widgetContainer.appendChild(widgetContent);
        
        // 添加到容器
        container.appendChild(widgetContainer);
        
        // 根据组件类型渲染内容
        const widgetType = this.widgetTypes[widget.type];
        if (widgetType && widgetType.render) {
            try {
                widgetType.render(widgetContent, widget);
            } catch (error) {
                console.error(`渲染组件 ${widget.id} 时出错:`, error);
                widgetContent.innerHTML = '<div class="widget-error">组件渲染失败</div>';
            }
        } else {
            widgetContent.innerHTML = `<div class="widget-placeholder">未知组件类型: ${widget.type}</div>`;
        }
        
        return widgetContainer;
    }

    // 渲染折线图组件
    renderLineChart(container, config) {
        const canvas = document.createElement('canvas');
        container.appendChild(canvas);
        
        // 使用Chart.js创建图表
        if (window.Chart) {
            const ctx = canvas.getContext('2d');
            
            // 模拟数据
            const labels = Array.from({length: 20}, (_, i) => `${i * 5}s`);
            const datasets = (config.fields || ['value']).map((field, index) => ({
                label: field,
                data: Array.from({length: 20}, () => Math.random() * 100),
                borderColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'][index % 5],
                backgroundColor: 'rgba(0, 0, 0, 0.1)',
                tension: 0.4
            }));
            
            new Chart(ctx, {
                type: 'line',
                data: { labels, datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false, // 禁用动画以提高性能
                    scales: {
                        x: { display: true, title: { display: true, text: '时间' } },
                        y: { display: true, beginAtZero: true }
                    }
                }
            });
            
            // 如果配置了数据源，设置数据更新
            if (config.dataSource && realTimeSystem.modules.dataStream) {
                this.setupDataUpdates(canvas, config);
            }
        } else {
            container.innerHTML = '<div class="chart-placeholder">图表库未加载</div>';
        }
    }

    // 渲染柱状图组件
    renderBarChart(container, config) {
        const canvas = document.createElement('canvas');
        container.appendChild(canvas);
        
        // 使用Chart.js创建图表
        if (window.Chart) {
            const ctx = canvas.getContext('2d');
            
            // 模拟数据
            const labels = ['A', 'B', 'C', 'D', 'E'];
            const datasets = (config.fields || ['value']).map((field, index) => ({
                label: field,
                data: Array.from({length: labels.length}, () => Math.random() * 100),
                backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'][index % 5]
            }));
            
            new Chart(ctx, {
                type: 'bar',
                data: { labels, datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: { beginAtZero: true }
                    }
                }
            });
        } else {
            container.innerHTML = '<div class="chart-placeholder">图表库未加载</div>';
        }
    }

    // 渲染饼图组件
    renderPieChart(container, config) {
        const canvas = document.createElement('canvas');
        container.appendChild(canvas);
        
        // 使用Chart.js创建图表
        if (window.Chart) {
            const ctx = canvas.getContext('2d');
            
            // 模拟数据
            const labels = ['类别1', '类别2', '类别3', '类别4', '类别5'];
            const data = Array.from({length: labels.length}, () => Math.random() * 100);
            const backgroundColor = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF'];
            
            new Chart(ctx, {
                type: 'pie',
                data: { labels, datasets: [{ data, backgroundColor }] },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom' }
                    }
                }
            });
        } else {
            container.innerHTML = '<div class="chart-placeholder">图表库未加载</div>';
        }
    }

    // 渲染状态卡片组件
    renderStatusCard(container, config) {
        const metrics = config.metrics || [];
        
        metrics.forEach(metric => {
            const metricCard = document.createElement('div');
            metricCard.className = 'metric-card';
            metricCard.innerHTML = `
                <div class="metric-name">${metric}</div>
                <div class="metric-value">--</div>
                <div class="metric-change"><span class="neutral">--</span></div>
            `;
            container.appendChild(metricCard);
        });
        
        // 设置数据更新
        if (config.dataSource && realTimeSystem.modules.dataStream) {
            const dataStream = realTimeSystem.modules.dataStream;
            dataStream.on(`${config.dataSource}:updated`, (data) => {
                metrics.forEach(metric => {
                    if (data[metric] !== undefined) {
                        const valueElement = container.querySelector(`.metric-name:contains('${metric}') + .metric-value`);
                        if (valueElement) {
                            valueElement.textContent = realTimeSystem.utils.formatNumber(data[metric]);
                        }
                    }
                });
            });
        }
    }

    // 渲染数据表格组件
    renderDataTable(container, config) {
        const table = document.createElement('table');
        table.className = 'data-table';
        
        // 创建表头
        const thead = document.createElement('thead');
        thead.innerHTML = '<tr><th>时间戳</th><th>数据</th></tr>';
        table.appendChild(thead);
        
        // 创建表格体
        const tbody = document.createElement('tbody');
        table.appendChild(tbody);
        
        container.appendChild(table);
        
        // 设置数据更新
        if (config.dataSource && realTimeSystem.modules.dataStream) {
            const dataStream = realTimeSystem.modules.dataStream;
            dataStream.on(`${config.dataSource}:updated`, (data) => {
                const row = tbody.insertRow(0); // 插入到顶部
                const timestampCell = row.insertCell(0);
                const dataCell = row.insertCell(1);
                
                timestampCell.textContent = new Date(data.timestamp || Date.now()).toLocaleTimeString();
                dataCell.textContent = JSON.stringify(data).substring(0, 50) + '...';
                
                // 限制行数
                if (tbody.rows.length > 10) {
                    tbody.deleteRow(tbody.rows.length - 1);
                }
            });
        }
    }

    // 渲染金融卡片组件
    renderFinancialCards(container, config) {
        const symbols = config.symbols || [];
        
        symbols.forEach(symbol => {
            const card = document.createElement('div');
            card.className = 'financial-card';
            card.innerHTML = `
                <div class="symbol">${symbol}</div>
                <div class="price">--</div>
                <div class="change"><span class="neutral">--</span></div>
            `;
            container.appendChild(card);
        });
    }

    // 渲染设备网格组件
    renderDeviceGrid(container, config) {
        const deviceGrid = document.createElement('div');
        deviceGrid.className = 'device-grid';
        container.appendChild(deviceGrid);
        
        // 模拟设备数据
        for (let i = 1; i <= 6; i++) {
            const deviceCard = document.createElement('div');
            deviceCard.className = 'device-card';
            deviceCard.innerHTML = `
                <div class="device-id">设备 ${i}</div>
                <div class="device-status">
                    <span class="status-indicator ${i % 3 === 0 ? 'offline' : 'online'}"></span>
                    ${i % 3 === 0 ? '离线' : '在线'}
                </div>
                <div class="device-data">
                    <div>温度: ${Math.floor(Math.random() * 30) + 20}°C</div>
                    <div>湿度: ${Math.floor(Math.random() * 40) + 40}%</div>
                </div>
            `;
            deviceGrid.appendChild(deviceCard);
        }
    }

    // 渲染告警计数器组件
    renderAlertCounter(container, config) {
        const counters = {
            critical: 0,
            high: 0,
            medium: 0,
            low: 0
        };
        
        const counterContainer = document.createElement('div');
        counterContainer.className = 'alert-counters';
        
        Object.entries(counters).forEach(([severity, count]) => {
            const counter = document.createElement('div');
            counter.className = `alert-counter severity-${severity}`;
            counter.innerHTML = `
                <div class="counter-label">${severity === 'critical' ? '严重' : 
                                          severity === 'high' ? '高' : 
                                          severity === 'medium' ? '中' : '低'}</div>
                <div class="counter-value">${count}</div>
            `;
            counterContainer.appendChild(counter);
        });
        
        container.appendChild(counterContainer);
        
        // 监听告警事件更新计数
        if (realTimeSystem.modules.alertEngine) {
            const alertEngine = realTimeSystem.modules.alertEngine;
            
            // 更新所有计数器显示
            const updateCounters = () => {
                const stats = alertEngine.getStatistics();
                Object.entries(stats.bySeverity).forEach(([severity, count]) => {
                    const valueElement = container.querySelector(`.alert-counter.severity-${severity} .counter-value`);
                    if (valueElement) {
                        valueElement.textContent = count;
                    }
                });
            };
            
            // 监听告警事件
            alertEngine.on('alert:triggered', updateCounters);
            alertEngine.on('alert:resolved', updateCounters);
            alertEngine.on('alerts:cleared', updateCounters);
            
            // 初始化计数
            updateCounters();
        }
    }

    // 渲染仪表盘图表组件
    renderGaugeChart(container, config) {
        const canvas = document.createElement('canvas');
        container.appendChild(canvas);
        
        // 简单的仪表盘渲染
        if (window.Chart) {
            const ctx = canvas.getContext('2d');
            
            // 模拟数据
            const value = Math.random() * 100;
            
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    datasets: [{
                        data: [value, 100 - value],
                        backgroundColor: ['#36A2EB', '#E9ECEF'],
                        borderWidth: 0
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '80%',
                    plugins: {
                        tooltip: { enabled: false },
                        legend: { display: false }
                    }
                }
            });
            
            // 添加中心文本
            const centerText = document.createElement('div');
            centerText.className = 'gauge-center-text';
            centerText.textContent = `${Math.round(value)}%`;
            centerText.style.position = 'absolute';
            centerText.style.top = '50%';
            centerText.style.left = '50%';
            centerText.style.transform = 'translate(-50%, -50%)';
            centerText.style.fontSize = '1.5rem';
            centerText.style.fontWeight = 'bold';
            container.appendChild(centerText);
        } else {
            container.innerHTML = '<div class="chart-placeholder">图表库未加载</div>';
        }
    }

    // 设置数据更新
    setupDataUpdates(canvas, config) {
        if (!realTimeSystem.modules.dataStream) return;
        
        const dataStream = realTimeSystem.modules.dataStream;
        const chart = Chart.getChart(canvas);
        if (!chart) return;
        
        // 初始数据加载
        const initialData = dataStream.getData(config.dataSource, {
            limit: config.limit || 20
        });
        
        // 更新图表数据
        if (initialData.length > 0) {
            // 这里应该根据实际的数据源和字段进行更新
            // 简化版本，实际应该根据配置的字段更新对应的数据集
        }
        
        // 监听数据更新事件
        dataStream.on(`${config.dataSource}:updated`, (data) => {
            // 这里应该实现实时数据更新逻辑
            // 简化版本，实际应该根据配置的字段和图表类型进行更新
        });
    }

    // 获取所有仪表盘
    getDashboards() {
        return [...this.dashboards];
    }

    // 获取活动仪表盘
    getActiveDashboard() {
        return this.dashboards.find(d => d.id === this.activeDashboardId) || null;
    }

    // 获取组件类型
    getWidgetTypes() {
        return { ...this.widgetTypes };
    }

    // 添加组件到仪表盘
    addWidgetToDashboard(dashboardId, widgetConfig) {
        const dashboard = this.dashboards.find(d => d.id === dashboardId);
        if (!dashboard) return false;
        
        const widget = {
            id: widgetConfig.id || `widget_${Date.now()}`,
            type: widgetConfig.type,
            title: widgetConfig.title || '未命名组件',
            position: widgetConfig.position || { x: 0, y: 0, width: 1, height: 1 },
            ...widgetConfig
        };
        
        dashboard.widgets.push(widget);
        
        // 保存到本地存储
        this.saveDashboardsToStorage();
        
        // 如果是活动仪表盘，重新渲染
        if (dashboardId === this.activeDashboardId) {
            this.renderActiveDashboard();
        }
        
        return widget;
    }

    // 从仪表盘移除组件
    removeWidgetFromDashboard(dashboardId, widgetId) {
        const dashboard = this.dashboards.find(d => d.id === dashboardId);
        if (!dashboard) return false;
        
        const initialLength = dashboard.widgets.length;
        dashboard.widgets = dashboard.widgets.filter(w => w.id !== widgetId);
        
        if (dashboard.widgets.length < initialLength) {
            // 保存到本地存储
            this.saveDashboardsToStorage();
            
            // 如果是活动仪表盘，重新渲染
            if (dashboardId === this.activeDashboardId) {
                this.renderActiveDashboard();
            }
            
            return true;
        }
        
        return false;
    }

    // 保存仪表盘到本地存储
    saveDashboardsToStorage() {
        try {
            localStorage.setItem('dashboards', JSON.stringify(this.dashboards));
            return true;
        } catch (error) {
            console.error('保存仪表盘到本地存储时出错:', error);
            return false;
        }
    }

    // 从本地存储加载仪表盘
    loadDashboardsFromStorage() {
        try {
            const storedDashboards = localStorage.getItem('dashboards');
            if (storedDashboards) {
                const parsedDashboards = JSON.parse(storedDashboards);
                if (Array.isArray(parsedDashboards)) {
                    // 只加载非默认仪表盘，避免覆盖默认仪表盘
                    parsedDashboards.forEach(dashboard => {
                        if (!dashboard.isDefault && !this.dashboards.find(d => d.id === dashboard.id)) {
                            this.dashboards.push(dashboard);
                        }
                    });
                    
                    console.log(`从本地存储加载了 ${parsedDashboards.length} 个自定义仪表盘`);
                    
                    // 尝试恢复之前的活动仪表盘
                    const activeDashboardId = localStorage.getItem('active_dashboard_id');
                    if (activeDashboardId && this.dashboards.find(d => d.id === activeDashboardId)) {
                        this.setActiveDashboard(activeDashboardId);
                    }
                    
                    return true;
                }
            }
        } catch (error) {
            console.error('从本地存储加载仪表盘时出错:', error);
        }
        
        return false;
    }

    // 注册监听器
    on(event, callback) {
        if (!this.listeners[event]) {
            this.listeners[event] = [];
        }
        this.listeners[event].push(callback);
        
        return () => {
            this.listeners[event] = this.listeners[event].filter(cb => cb !== callback);
        };
    }

    // 触发事件
    emit(event, data) {
        if (this.listeners[event]) {
            this.listeners[event].forEach(callback => {
                try {
                    callback(data);
                } catch (error) {
                    console.error(`处理${event}事件时出错:`, error);
                }
            });
        }
    }

    // 停止多仪表盘管理
    stop() {
        console.log('多仪表盘管理模块已停止');
    }
}

// 创建并注册多仪表盘管理实例
const multiDashboard = new MultiDashboard();
realTimeSystem.registerModule('multiDashboard', multiDashboard);

// 导出多仪表盘管理
window.multiDashboard = multiDashboard;